package com.teamin.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.cj.core.util.StringUtils;
import com.teamin.config.ErrorCode;
import com.teamin.entity.*;
import com.teamin.security.AESUtils;
import com.teamin.service.*;
import com.teamin.service.impl.MessageServiceImpl;
import com.teamin.service.impl.WebsocketServiceImpl;
import com.teamin.service.labelService.LabelService;
import com.teamin.vo.CircleVO;
import com.teamin.web.entityJsonFilter.CircleJsonFilter;
import com.teamin.web.exception.GlobalErrorInfoException;
import com.teamin.web.model.ErrorInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/v1")
@Api(basePath = "/v1",description = "跟圈子相关的接口",tags = "圈子")
public class CircleController extends BaseController {


	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private CircleService circleService;

	@Autowired
	private MessageServiceImpl messageService;

	@Autowired
	private TaskService taskService;

	@Autowired
	private UserService userService;

	@Autowired
	private WxGroupService wxGroupService;

	@Autowired
	private WxService wxService;

	@Autowired
	private WebsocketServiceImpl websocketService ;

	@Autowired
	private LogService logService;

	@Autowired
	private LabelService labelService;

	@ApiOperation("获取圈子中所关联的微信群")
	@RequestMapping(value = "/circles/{circleId}/wxgroups", method = RequestMethod.GET)
	@ApiResponse(code = 200,message = "",response = WxGroupEntity.class)
	public List<WxGroupEntity> getGroupsByCircle(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
												 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		return wxGroupService.getGroupsByCircle(circleId) ;
	}

	@ApiOperation("圈子添加微信群 圈子绑定微信群ID号 一个圈子可以绑定多个微信群")
	@ApiResponse(code = 200,message = "",response = String.class)
	@RequestMapping(value = "/circles/{circleId}/wxgroups", method = RequestMethod.POST)
	public String linkWxGroupAndCircle( @ApiParam("微信登录后返回的CODE") String code,
										@ApiParam("加密的数据") @RequestParam(required = true) String encryptedData,
										@ApiParam("微信密钥") @RequestParam(required = true) String iv,
										@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
										@ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
										@ApiParam("分享时所带的加密串") String sign) throws Exception {

		ShareInvite json = JSONObject.parseObject(AESUtils.decrypt(sign, CIRCLE_SIGN_KEY),ShareInvite.class) ;
		if(json == null || !circleId.equals(json.getControlId())) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
		}

		CircleEntity circleTemp = circleService.selectCircleById(json.getControlId(), json.getControlUser());

		//圈子已被解散
		if(circleService.selectMemberCount(json.getControlId()) == 0) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_DISMISS));
		}

		// 获取微信群
		WxGroupEntity wxGroupEntity = wxService.decrypedWxGroupEntity(code, encryptedData, iv,loginUserId);

		if(wxGroupEntity != null && !StringUtils.isNullOrEmpty(wxGroupEntity.getGroupId())) {

			//是分享圈子 并且有权限分享圈子则 返回圈子信息
			if (  circleTemp.getCreaterId() != loginUserId) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.BIND_GROUP_CIRCLE));
			}
			wxGroupService.saveUserGroup(loginUserId,wxGroupEntity.getGroupId());
		}else {
			logService.insertCircleLog(circleId, LogService.HANDLE.ADD, LogService.CircleHandleField.CIRCLE_SHARE_USER,loginUserId,circleService.getUserName(circleId,loginUserId), null) ;
		}

		CircleEntity circle = circleService.selectCircleById(circleId, loginUserId);;
		if(circle == null || !circle.getUserCanMemberShare()) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBID_SHARE));
		}

		// 关联微信群
		if(wxGroupEntity != null && (ShareInvite.CONTROL_SHARE_CIRCLE.equals(json.getControlType()) || ShareInvite.CONTROL_INVITE_CIRCLE.equals(json.getControlType()))) {
			wxGroupService.addWxGroupEntityToCircle(wxGroupEntity, circleId,loginUserId);
			logService.insertCircleLog(circleId, LogService.HANDLE.ADD, LogService.CircleHandleField.CIRCLE_SHARE_GROUP,loginUserId,circleService.getUserName(circleId,loginUserId),wxGroupEntity.getGroupId()) ;
		}
		return "success";
	}

	@ApiOperation("解除圈子跟群的绑定关系")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/wxgroups", method = RequestMethod.DELETE)
	public void deleteCircleOpGidBind(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
									  @ApiParam("openGId") @RequestParam(required = true) String openGid,
									  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {

		// 不属于圈子
		if (!circleService.isCreater(circleId,loginUserId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		wxGroupService.removeWxGroupEntityFromCircle(openGid,circleId) ;
	}


	@ApiOperation("查询一个cirlce")
	@ApiResponse(code = 200,message = "",response = CircleEntity.class)
	@RequestMapping(value = "/circles/{circleId}", method = RequestMethod.GET)
	public CircleEntity getCirlce(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
								  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId)
			throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		return circleService.selectCircleWithUsersById(circleId,loginUserId);
	}

	@ApiOperation("删除cirlce")
	@ApiResponse(code = 200,message = "",response = String.class)
	@RequestMapping(value = "/circles/{circleId}", method = RequestMethod.DELETE)
	public String deleteCirlce(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
							   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		if (true)
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.UNFINISH_METHORD));

		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_DELETE_CIRCLE));
		}
		circleService.deleteCircleById(circleId);
		return "success";
	}

	@ApiOperation("添加cirlce")
	@ApiResponse(code = 200,message = "",response = CircleEntity.class)
	@RequestMapping(value = "/circles", method = RequestMethod.POST)
	public CircleEntity addCircle(@ApiParam("圈子的实体") @ModelAttribute CircleEntity circleEntity,
								  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		return circleService.addCircleEntity(circleEntity, loginUserId);
	}

	@ApiOperation("修改cirlce")
	@ApiResponse(code = 200,message = "",response = Object.class)
	@RequestMapping(value = "/circles/{circleId:\\d+}", method = RequestMethod.PUT)
	public Object updateCircle(@ApiParam("圈子的ID") @PathVariable("circleId") Long circleId,
							   @ApiParam("圈子的实体") @ModelAttribute CircleEntity circleEntity,
							   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
							   @RequestAttribute("userFlag") String userFlag) throws Exception {

		// 只有创建者才要能修改
		if (!circleService.isCreater(circleId,loginUserId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.NEED_CIRCLE_ADMIN));
		}
		circleService.updateCircle(circleEntity,true,loginUserId);
		// 不返回用户列表
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.addMixIn(CircleEntity.class, CircleJsonFilter.class);
		String string = objectMapper.writeValueAsString(circleService.selectCircleWithUsersById(circleId,loginUserId));
		//发送socket通知
        websocketService.sendCircle(loginUserId,circleId, WebsocketService.CirclePropertise.BASE, WebsocketService.Control.MODIFY,circleEntity,userFlag);
		return JSON.parseObject(string, Feature.OrderedField);
	}

	@ApiOperation("查询用户的全部cirlce")
	@ApiResponse(code = 200,message = "返回一个圈子列表",response = CircleEntity.class)
	@RequestMapping(value = "/circles", method = RequestMethod.GET)
	public List<CircleEntity> getCirclesByUserId(@ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		List<CircleEntity> list = circleService.selectCircleAndUser(loginUserId);
		return list;
	}

	@RequestMapping(value = "/v012/circles", method = RequestMethod.GET)
	@ApiOperation("获取用户所在的所有圈子 包括最后一条消息")
	@ApiResponse(code = 200,message = "",response = CircleVO.class)
	public List<CircleVO> selectCircleAndUserV012(@RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		return circleService.selectUserCircleV012(loginUserId,null);
	}

	@ApiOperation("获取用户所在的单个圈子 包括最后一条消息")
	@ApiResponse(code = 200,message = "",response = CircleVO.class)
	@RequestMapping(value = "/v012/circles/{circleId}", method = RequestMethod.GET)
	public CircleVO selectCircleAndUserV012(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											@ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_DELETE_CIRCLE));
		}
		return circleService.selectCircleV012(loginUserId,circleId);
	}

	@ApiOperation("一个circle下的全部任务")
	@ApiResponse(code = 200,message = "返回任务列表",response = TaskEntity.class)
	@RequestMapping(value = "/circles/{circleId}/tasks", method = RequestMethod.GET)
	public List<TaskEntity> getTasksByCircle(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											 @ApiParam("任务排序方式") String order,
											 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,String filter) throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}
		int o = 0;
		try {
			o = Integer.parseInt(order);
		} catch (Exception e) {

		}

		return taskService.selectByCircle(circleId, o,filter);
	}

	@ApiOperation("获取圈子下的所有任务")
	@ApiResponse(code = 200,message = "返回任务列表",response = TaskEntity.class)
	@RequestMapping(value = "/010/circles/{circleId}/tasks", method = RequestMethod.GET)
	public List<TaskEntity> getTasksByCircleV010(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
												 @ApiParam("排序,已废弃此字段")String order,
												 @ApiParam(hidden = true)@RequestAttribute("loginUserId") Long loginUserId,
												 @ApiParam("要过滤的内容,只过滤标题跟描述") String filter,
												 @ApiParam("任务状态过滤,0未完成,3表示已完成") Integer state,
												 @ApiParam("标签过滤,多个标签ID 用逗号分隔") String filterLabels,
												 @ApiParam("执行者ID 多个执行者用逗号分隔") String assignerId) throws Exception {

		if(state==null || !(state==3 || state==0)){
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CHECK_PARAMETER_FALSE));
		}

		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}
		List<String> labels = new ArrayList<>() ;

		if(!StringUtils.isNullOrEmpty(filterLabels)){
			labels = Arrays.asList(filterLabels.split(",")) ;
		}

		int o = 0;
		try {
			o = Integer.parseInt(order);
		} catch (Exception e) {

		}
		return taskService.selectByCircleV010(circleId, o,filter,labels,loginUserId,state,assignerId);
	}

	@ApiOperation("添加任务到circle")
	@ApiResponse(code = 200,message = "返回任务详情",response = TaskEntity.class)
	@RequestMapping(value = "/circles/{circleId}/tasks", method = RequestMethod.POST)
	public TaskEntity addTaskToCircle(@ApiParam("任务信息") @Valid @ModelAttribute TaskEntity taskEntity,
									  @ApiParam("任务提醒") @Valid TaskRemindEntity taskRemindEntity,
									  @ApiParam(hidden = true) String planFinishTime,
									  @ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
									  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,String labelIds,
									  @ApiParam(hidden = true) @RequestAttribute("userFlag") String userFlag) throws Exception {
		// 用户不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}

		// 任务不属于圈子
		if (taskEntity.getParentTaskId() != null) {

			if(!circleService.existTask(circleId, taskEntity.getParentTaskId())) {
				throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_NOT_EXIST_TASK));
			}

			if(taskService.isdeleted(taskEntity.getParentTaskId())) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_ISDELETED));
			}

			if(taskService.isSubTask(taskEntity.getParentTaskId())) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.TASK_IS_SUB_TASK));
			}
		}

		// 有指定执行人
		if (taskEntity.getAssignerId() != null && taskEntity.getAssignerId() != 0L) {
			// 不属于圈子
			if (!userService.userInCircle(taskEntity.getAssignerId(), circleId)) {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_ASSIGNER_FROM_CIRCLE_NULL));
			}
		}

		taskEntity.setCreaterId(loginUserId);

		taskService.addTaskToCircle(taskEntity,circleId,loginUserId);
		taskEntity = taskService.selectTaskById(taskEntity.getTaskId());

		//更新任务结束时间或更新任务提醒
		if(taskRemindEntity != null && taskRemindEntity.getRemindMoveUpType()!= null && taskEntity.getPlanFinishTime() != null && taskRemindEntity.getRemindMoveUp() !=0) {
			taskRemindEntity.setTaskId(taskEntity.getTaskId());
			TaskRemindEntity tr = taskService.updateTaskRemind(taskEntity.getTaskId(), taskEntity.getPlanFinishTime(), taskRemindEntity, loginUserId);
			taskEntity.setTaskRemind(tr);
		}

		// 创建新任务通知
		Long assignerId = taskEntity.getAssignerId();
		if (assignerId != null && !assignerId.equals(loginUserId)) {
			messageService.createNewTaskMessage(taskEntity, circleId, loginUserId,userFlag);
		}

		//任务中添加标签
		if(!StringUtils.isNullOrEmpty(labelIds)) {
			CircleEntity circleEntity = circleService.selectCircleByTask(taskEntity.getTaskId(), loginUserId);;
			String[] lb = labelIds.split(",");
			LabelTaskEntity labelTaskEntity = new LabelTaskEntity();
			labelTaskEntity.setTaskId(taskEntity.getTaskId());
			for(String l :lb) {
				labelTaskEntity.setLabelId(Long.parseLong(l));
				//规则判断
				if (labelService.existCircleLabel(circleEntity.getCircleId(),Long.parseLong(l)) && !labelService.existTaskLabel(taskEntity.getTaskId(),Long.parseLong(l))) {
					labelService.insertToTask(labelTaskEntity,circleId,loginUserId,userFlag) ;
				}
			}
			taskEntity = taskService.selectTaskById(taskEntity.getTaskId());
		}

        //发送socket通知
        websocketService.sendCircle(loginUserId,circleId, WebsocketService.CirclePropertise.TASK, WebsocketService.Control.ADD,taskEntity,userFlag);
		return taskEntity;
	}

	@ApiOperation("一个circle下的全部成员")
	@ApiResponse(code = 200,message = "返回圈子下的所有成员",response = CircleUserEntity.class)
	@RequestMapping(value = "/circles/{circleId}/users", method = RequestMethod.GET)
	public List<CircleUserEntity> getUsers(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
										   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId)
			throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}
		return circleService.selectMemberToCircle(circleId,null);
	}

	@ApiOperation("更新圈子中用户的信息")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/user/{userId}", method = RequestMethod.PUT)
	public void updateUser(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
						   @ApiParam("用户信息") @Valid CircleUserEntity circleUserEntity,
						   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
						   @ApiParam("要添加的用户ID") @PathVariable("userId") Long userId,
						   @ApiParam(hidden = true) @RequestAttribute("userFlag") String userFlag,
						   @ApiParam(hidden = true) BindingResult bindingResult)
			throws Exception {
		CircleUserEntity us = circleService.selectMemberCircle(circleId, loginUserId);

		if(us != null && (userId==loginUserId || us.isCreater())) {
			circleService.updateUser(circleId,userId,circleUserEntity.getNickName(),circleUserEntity.getCirclePhone(),circleUserEntity.getCircleEmail(),circleUserEntity.getCircleJob(),loginUserId, us.isCreater()) ;
		}else {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.PERMISSION_UPDATE_USER));
		}
		//发送socket通知
		websocketService.sendCircle(loginUserId,circleId, WebsocketService.CirclePropertise.USER, WebsocketService.Control.MODIFY,userId,userFlag);
	}


	/**
	 * FIXME 现没有单独添加成员的接口
	 * 添加成员到circle
	 * @param circleId
	 * @param userId
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value = "/circles/{circleId}/users/{userId}", method = RequestMethod.POST)
//	public List<CircleUserEntity> addUser(@PathVariable("circleId") Long circleId, @PathVariable("userId") Long userId,
//										  @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
//
//		// 不是自己,抛出异常,<当前用户只能添加当前用户到圈子中不能添加其他成员到圈子中>
//		if (userId != loginUserId) {
//			throw new GlobalErrorInfoException(
//					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CANNOT_ADD_OTHERS_TO_CIRCLE));
//		}
//
//		// 不存在圈子，抛出异常
//		if (!circleService.circleExist(circleId)) {
//			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_CIRCLE_NULL));
//		}
//
//		// 不存在用户，抛出异常
//		// if (!userService.userExist(userId)) {
//		// throw new GlobalErrorInfoException(new
//		// ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_NULL));
//		// }
//
//		// 用户已经在圈子，返回成功
//		if (userService.userInCircle(userId, circleId)) {
//			return circleService.selectMemberFromCircle(circleId);
//		}
//
//		circleService.addMemberToCircle(circleId, userId);
//		return circleService.selectMemberFromCircle(circleId);
//	}

	@ApiOperation("从circle移除成员")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/users/{userId}", method = RequestMethod.DELETE)
	public List<CircleUserEntity> deleteUser(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											 @ApiParam("要删除的用户ID") @PathVariable("userId") Long userId,
											 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
			@RequestAttribute("userFlag") String userFlag) throws Exception {
			CircleUserEntity userEntity = circleService.selectMemberCircle(circleId, loginUserId);
			int re  = 0 ;
			// 如果是创建者或者要移除的用户是当前登录用户,
			if (userEntity.isCreater() || loginUserId.equals(userId)) {
				re = circleService.removeMemberFromCircle(circleId, userId,loginUserId,userFlag);
			}else {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CANNOT_REMOVE_CREATER_F_CIRCLE));
			}
		return circleService.selectMemberToCircle(circleId,null);
	}

	@ApiOperation("从circle移除成员批量")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/user", method = RequestMethod.DELETE)
	public List<CircleUserEntity> deleteUserBatch(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
												  @ApiParam("要删除的用户ID 用逗号分隔") @RequestParam("userId") String userId,
												  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
												  @ApiParam(hidden = true) @RequestAttribute("userFlag") String userFlag) throws Exception {

		if(userId != null) {
			String[] userIds = userId.split(",");;
			CircleUserEntity userEntity = circleService.selectMemberCircle(circleId, loginUserId);
			int re  = 0 ;
			// 如果是创建者或者要移除的用户是当前登录用户,
			if (userEntity.isCreater()) {
				re = circleService.removeMembersFromCircle(circleId, userIds,loginUserId,userFlag);
			}else {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CANNOT_REMOVE_OTHERS_F_CIRCLE));
			}
		}
		return circleService.selectMemberToCircle(circleId,null);
	}

	@ApiOperation("一个circle下的全部消息 包括过期任务")
	@ApiResponse(code = 200,message = "返回消息列表 老接口",response = ResponseEntity.class)
	@RequestMapping(value = "/circles/{circleId}/messages", method = RequestMethod.GET)
	public ResponseEntity<Object> getMessagesByCircle(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
													  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId) throws Exception {
		// 不属于圈子
		if (!userService.userInCircle(loginUserId, circleId)) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
		}
		// 过期、七天、三天任务
		Map<String, Object> tasks = taskService.getNeedNoticeTasks(circleId, loginUserId);
		// 完成、新建消息
		List<MessageEntity> messageEntities = messageService.getMessageByUserAndCircle(loginUserId,
				circleId);
		// 整合的消息
		LinkedHashMap<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("messages", messageEntities);
		map.putAll(tasks);
		return new ResponseEntity<Object>(map, HttpStatus.OK);
	}

	@ApiOperation("获取圈子分享,邀请的有效签名")
	@ApiResponse(code = 200,message = "返回签名对像",response = JSONObject.class)
	@RequestMapping(value = "/circles/{circleId}/action/sign/{type}", method = RequestMethod.GET)
	public JSONObject getShareSign(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
								   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
								   @ApiParam("签名类型(share_circle|invite_circle) 表示分享或邀请") @PathVariable("type") String type) throws GlobalErrorInfoException {

		if (!(ShareInvite.CONTROL_SHARE_CIRCLE.equals(type) || ShareInvite.CONTROL_INVITE_CIRCLE.equals(type))) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
		}

		CircleEntity circle = circleService.selectCircleById(circleId, loginUserId);

		//不是圈子中的成员
		if (circle == null ) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}

		//没有权限分享圈子
		if (ShareInvite.CONTROL_SHARE_CIRCLE.equals(type) && !circle.getUserCanMemberShare()) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBID_SHARE));
		}

		//没有权限邀请成员圈子
		if (ShareInvite.CONTROL_INVITE_CIRCLE.equals(type) && !circle.getUserCanMemberInvite()) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBID_INVITE));
		}

		ShareInvite cs = new ShareInvite();
		cs.setControlId(circleId);
		cs.setControlUser(loginUserId);
		if (ShareInvite.CONTROL_SHARE_CIRCLE.equals(type)) {
			cs.setControlType(ShareInvite.CONTROL_SHARE_CIRCLE);
		} else if (ShareInvite.CONTROL_INVITE_CIRCLE.equals(type)) {
			cs.setControlType(ShareInvite.CONTROL_INVITE_CIRCLE);
		}
		cs.setCreateTime(new Date());
		JSONObject jSing = new JSONObject();
		jSing.put("sign", AESUtils.encrypt(JSONObject.toJSONString(cs), CIRCLE_SIGN_KEY));
		jSing.put("expire", CIRCLE_SIGN_TIME);
		return jSing;
		}

	@ApiOperation("处理圈子分享,邀请")
	@ApiResponse(code = 200,message = "返回圈子信息",response = CircleEntity.class)
	@RequestMapping(value = "/circles/{circleId}/sign", method = RequestMethod.POST)
	public CircleEntity controlShareSign(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
										 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
										 @ApiParam("签名") @RequestParam(value = "sign", required = true) String sign,
										 @ApiParam("微信加密的数据") @RequestParam String encryptedData,
										 @ApiParam("微信数据解密 的密钥") @RequestParam String iv,
										 @ApiParam(hidden = true) @RequestAttribute("userFlag") String userFlag) throws GlobalErrorInfoException, IOException {

		//获取群ID
		String groupId = wxService.getGroupId(encryptedData, iv, loginUserId);
		if(!StringUtils.isNullOrEmpty(groupId)) {
			wxGroupService.saveUserGroup(loginUserId,groupId);
		}

		ShareInvite json = null ;
		try{
			json = JSONObject.parseObject(AESUtils.decrypt(sign, CIRCLE_SIGN_KEY),ShareInvite.class) ;
		}catch(Exception e) {
		}

		if(json == null ) {
			//不存在圈子
			if(!circleService.circleExist(circleId)){
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_CIRCLE_NULL));
			}

			// 用户在圈子中
			if (userService.userInCircle(loginUserId, circleId)) {
				return circleService.selectCircleWithUsersById(circleId,loginUserId);
			}else {
				throw new GlobalErrorInfoException(
						new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_USER_FROM_CIRCLE_NULL));
			}
		}else if(json != null && (json.getCreateTime().getTime()+(CIRCLE_SIGN_TIME * 1000)) < new Date().getTime() ) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_SIGN_EXPRIE));
		}else if(json != null && !circleId.equals(json.getControlId())) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_ERROR_TYPE));
		}

		//if(ShareInvite.CONTROL_SHARE_CIRCLE.equals(json.getControlType()) || ShareInvite.CONTROL_INVITE_CIRCLE.equals(json.getControlType())) {
		//不存在圈子
		if(!circleService.circleExist(json.getControlId())){
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FIND_CIRCLE_NULL));
		}

		CircleEntity circle = circleService.selectCircleById(json.getControlId(), json.getControlUser());

		//圈子已被解散
		if(circleService.selectMemberCount(json.getControlId()) == 0) {
			throw new GlobalErrorInfoException(
					new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.CIRCLE_DISMISS));
		}
		return circleService.addUserToCircle(circle,circleId,loginUserId,json,groupId,userFlag) ;
	}

	@ApiOperation("圈子置顶")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/action/stick", method = RequestMethod.PUT)
	public void updateUser(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
						   @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long loginUserId,
						   @ApiParam("置顶,1表示置顶,0表示取消置顶") @RequestParam(required = true) Integer stick)
			throws Exception {
		boolean inCircle1 = userService.userInCircle(loginUserId, circleId);
		if (!inCircle1) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		circleService.stickCircle(circleId,loginUserId,stick) ;
	}

	@ApiOperation("查看一个圈子的日志")
	@ApiResponse(code = 200,message = "返回圈子日志列表",response = CircleLogEntity.class)
	@RequestMapping(value = "/circles/{circleId}/log", method = RequestMethod.GET)
	public List<CircleLogEntity> getCircleLog(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											  @ApiParam(hidden = true)@RequestAttribute("loginUserId") Long loginUserId) throws Exception {

		boolean inCircle1 = userService.userInCircle(loginUserId, circleId);
		if (!inCircle1) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		return logService.selectCircleLog(circleId) ;
	}

	@ApiOperation("查询圈子用户刚刚创建的任务")
	@ApiResponse(code = 200,message = "返任务列表",response = TaskEntity.class)
	@RequestMapping(value = "/circles/{circleId}/justlook_creattask", method = RequestMethod.GET)
	List<TaskEntity> selectLookJustCreateTask(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											  @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long userId,
											  @ApiParam("取最近添加任务的条数,默认为3条") @RequestParam(defaultValue = "3",required = false) Long limit ) throws GlobalErrorInfoException {

		boolean inCircle1 = userService.userInCircle(userId, circleId);
		if (!inCircle1) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		return taskService.selectJustCreateTask(circleId,userId,limit) ;
	}

	@ApiOperation("查询圈子用户刚刚创建的任务的数量")
	@ApiResponse(code = 200,message = "返任未查看数量",response = JSONObject.class)
	@RequestMapping(value = "/circles/{circleId}/justlook_creattaskcount", method = RequestMethod.GET)
	JSONObject selectLookJustCreateTaskCount(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long userId) throws GlobalErrorInfoException {
		boolean inCircle1 = userService.userInCircle(userId, circleId);
		if (!inCircle1) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		JSONObject json = new JSONObject() ;
		json.put("jsutCreateTaskCount",taskService.selectLookJustCreateTaskCount(circleId,userId)) ;
		return json ;
	}

	@ApiOperation("更新圈子用户查看刚刚创建的任务的时间")
	@ApiResponse(code = 200,message = "",response = Void.class)
	@RequestMapping(value = "/circles/{circleId}/action/justlook_creattasktime", method = RequestMethod.PUT)
	public void updateLookJustCreateTaskTime(@ApiParam("圈子ID") @PathVariable("circleId") Long circleId,
											 @ApiParam(hidden = true) @RequestAttribute("loginUserId") Long userId,
											 @RequestAttribute("userFlag") String userFlag) throws GlobalErrorInfoException {
		boolean inCircle1 = userService.userInCircle(userId, circleId);
		if (!inCircle1) {
			throw new GlobalErrorInfoException(new ErrorInfo(HttpStatus.BAD_REQUEST, ErrorCode.FORBIDDEN_VIEW_CIRCLE));
		}
		taskService.updateLookJustCreateTaskTime(circleId,userId,userFlag) ;
	}

}